from flask import Flask, request
from flask_cors import CORS
from flask_caching import Cache
import hashlib
import os
from utils import response
import random
import string
from PIL import Image
import base64
from io import BytesIO

app = Flask(__name__)
CORS(app)
# 配置缓存
cache_config = {
    "CACHE_TYPE": "simple",  # 也可以是 "redis", "memcached" 等
}
app.config.from_mapping(cache_config)
cache = Cache(app=app, config={
    'CACHE_DEFAULT_TIMEOUT': 86400 * 7
})
host = '0.0.0.0'
port = 6301


@app.route('/')
def index():
    return response.success("HELLO SECRET")


# 添加图片
@app.route('/upload', methods=['POST'])
def upload():
    if 'file' not in request.files:
        return response.error(-1, '参数错误')
    file = request.files['file']
    if file.filename == "":
        return response.error(-1, '参数错误')
    ext = os.path.splitext(file.filename)[1].lower()
    image_ext = ['.png', '.jpg', '.jpeg', '.gif']
    type = ''
    if ext in image_ext:
        type = 'image'
    video_ext = ['.mp4', '.mov', '.mkv', '.avi']
    if ext in video_ext:
        type = 'video'
    if type == '':
        return response.error(-1, '只允许图片或视频')
    try:
        file_hash = gen_file_md5(file.read())
        file.seek(0)
        file_name = file_hash + ext
        file.save(os.path.join('static/media', file_name))

        key = generate_random_letters(12)
        thumb_path = ""
        if type is "image":
            thumbnail_size = (300, 300)
            create_thumbnail(os.path.join('static/media', file_name), os.path.join('static/media/thumb', file_name),
                             thumbnail_size)
            thumb_path = os.path.join('static/media/thumb', file_name)

        cache.set(key, {
            "path": os.path.join('static/media', file_name),
            "ts": request.form.get("ts"),
            "media_type": type,
            "thumb": thumb_path,
        })
        # 保存 key =》 value
        return response.success(
            {'key': key, 'path': "http://" + host + ":" + str(port) + "/" + os.path.join('static/media', file_name)})
    except Exception as e:
        return response.error(-1, str(e))


@app.route("/v/<key>", methods=['GET'])
def get_real_path(key):
    data = cache.get(key)
    if data is None:
        return response.error(-1, "资源不存在")
    # cache.delete(key)
    data['real_path'] = "http://" + host + ":" + str(port) + "/" + data.get('path')
    data['thumb'] = "http://" + host + ":" + str(port) + "/" + data.get('thumb')
    return response.success(data)


@app.route("/setcover", methods=['POST'])
def setcover():
    key = request.form.get('key')
    data = cache.get(key)
    if data is None:
        return response.error(-1, "资源不存在")
    cover = request.form.get('cover')
    _tmp = (data['path']).split('/')
    _tmp_name = (_tmp[-1]).split(".")
    out_path = os.path.join('static/media/thumb', _tmp_name[0] + ".png")
    save_base64_to_image(cover, out_path)
    data['thumb'] = out_path
    cache.set(key, data)
    return response.success(data)


def save_base64_to_image(base64_str, file_path):
    base64_str = base64_str.split('data:image/jpeg;base64,')[1]
    # 解码base64字符串
    image_data = base64.b64decode(base64_str)
    # 使用BytesIO创建一个可以读取的字节流
    image = Image.open(BytesIO(image_data))
    # 保存图片到指定路径
    image.save(file_path)
    print(f"图片已保存到: {file_path}")

def generate_random_letters(length):
    # 定义所有大写和小写字母
    letters = string.ascii_letters
    # 随机选择 length 个字母并返回字符串
    return ''.join(random.choice(letters) for i in range(length))


def gen_file_md5(file_content):
    return hashlib.md5(file_content).hexdigest()


def create_thumbnail(input_path, output_path, size):
    print(input_path, output_path)
    with Image.open(input_path) as img:
        img.thumbnail(size)
        img.save(output_path)


if __name__ == '__main__':
    app.run(host=host, port=port, debug=True)
